﻿using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Domain.PlcBytesObject;
using Zocono.WCS.Domain.PlcConnectPoolDomain;
using Zocono.WCS.Domain.ProcessModuleDomain;
using Zocono.WCS.Infrastructure.ApllicationDto.Enums;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;
using Zocono.WCS.Infrastructure.PlcCommon;
using Zocono.WCS.WMSApiDomain.WebApi;

namespace Zocono.WCS.Domain.EquipmentProcessDomain.PlanarMessage
{
    /// <summary>
    /// 平面设备扫码报文服务
    /// </summary>
    public class PlanarBatteryScanPlcActionBOMessageService : IPlanarActionMessageService
    {
        private readonly ILogUtil _LogUtil;
        private readonly ISnowflake _Snowflake;
        private readonly IPlcConnectionPool _PlcConnectionPool;
        private readonly IPlcWriteDbInfoRepository _PlcWriteDbInfoRepository;
        private readonly ITelegramRecordInfoRepository _TelegramRecordInfoRepository;
        private readonly IWorkTaskInfoRepository _workTaskInfoRepository;
        private readonly IPlcConnectionStateInfoRepository _IPlcConnectionStateInfoRepository;

        public PlanarBatteryScanPlcActionBOMessageService(ILogUtil logUtil
            , ISnowflake snowflake
            , IPlcConnectionPool plcConnectionPool
            , IPlcWriteDbInfoRepository plcWriteDbInfoRepository
            , ITelegramRecordInfoRepository telegramRecordInfoRepository
            , IWorkTaskInfoRepository workTaskInfoRepository
                , IPlcConnectionStateInfoRepository plcConnectionStateInfoRepository)
        {
            _LogUtil = logUtil;
            _Snowflake = snowflake;
            _PlcConnectionPool = plcConnectionPool;
            _PlcWriteDbInfoRepository = plcWriteDbInfoRepository;
            _TelegramRecordInfoRepository = telegramRecordInfoRepository;
            _workTaskInfoRepository = workTaskInfoRepository;
            _IPlcConnectionStateInfoRepository = plcConnectionStateInfoRepository;
        }

        public async Task ProcessActionMessageAsync(BytesObjectBase plcActionMessage, EquipmentDbObject planarEquipmentDbObject/*, BytesObjectBase plcStateMassge*/)
        {
            /*
            * 处理逻辑
            * 1. 调用扫码组盘接口
            * 2. 成功，则组织报文，写入plc
            */

           
            var scanPlcMessage = plcActionMessage as PlanarGeneralPlcActionBO;//Plc的动作报文
            if (scanPlcMessage == null)
            {
                return;
            }

            var plcMessage = plcActionMessage as PlanarGeneralPlcActionBO;//Plc的动作报文 


            var batteryMessage = planarEquipmentDbObject.bytesObjectBases.Find(o => o.ObjectType == "PlanarBatteryScanPlcActionBO") as PlanarBatteryScanPlcActionBO;


            #region 判断条码为空或存在重码提示
            var batteryScanPlcAction = planarEquipmentDbObject.bytesObjectBases.Find(o => o.ObjectType == "PlanarBatteryScanPlcActionBO") as PlanarBatteryScanPlcActionBO;
            var batteryCodeList = new List<string>();
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode1);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode2);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode3);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode4);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode5);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode6);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode7);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode8);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode9);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode10);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode11);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode12);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode13);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode14);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode15);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode16);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode17);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode18);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode19);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode20);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode21);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode22);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode23);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode24);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode25);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode26);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode27);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode28);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode29);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode30);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode31);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode32);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode33);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode34);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode35);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode36);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode37);
            batteryCodeList.Add(batteryScanPlcAction.BatteryCode38);
            //判断电池条码缺失或存在重码
            if(batteryCodeList.Where(s=> !string.IsNullOrEmpty(s)).Distinct().Count() < 38)// Distinct不同的
            {
                _LogUtil.Info($"[平面设备扫码报文服务]托盘电池条码缺失或存在重码");
                return;
            }
            #endregion


           // var plcStateBo = plcStateMassge as PlcOnLineStateBO;//Plc在线离线报文 没有设备信息
            //wcs-》plc报文
            var wcsMessage = planarEquipmentDbObject.bytesObjectBases.Find(o => o.ObjectType == "PlanarGeneralWcsActionBO") as PlanarGeneralWcsActionBO;
            PlcConnectionS7 plcConnect = _PlcConnectionPool.S7GetWritePlcConnection(scanPlcMessage.PlcConnectionID); ;//plc写入连接（不锁定）

            var plcIPStates = await _IPlcConnectionStateInfoRepository.GetFirstAsync(l => l.PlcConnectionID == plcMessage.PlcConnectionID && l.Connected == true);
            if (plcIPStates == null)
            {
                _LogUtil.Info($"请求巷道分配失败：设备编号{plcMessage.EquipmentCode}{plcConnect.IP}plc已离线");
                return;
            }

            //添加报文记录
            //var telegramUniqueIDObj = new { EquipmentCode = scanPlcMessage.EquipmentCode, PalletBarcode = scanPlcMessage.PalletBarcode, PlcTaskCode = scanPlcMessage.TaskCode, PlcActionType = scanPlcMessage.ActionType, WcsActionType = wcsMessage.ActionType };
            //var telegramUniqueIDJson = JsonConvert.SerializeObject(telegramUniqueIDObj);
            //var telgramRecord = await _TelegramRecordInfoRepository.AsSugarClient()
            //    .Queryable<TelegramRecordInfo>()
            //    .Where(it => it.EquipmentCode == plcMessage.EquipmentCode)
            //    .OrderBy(it => it.UpdateTime, SqlSugar.OrderByType.Desc)
            //    .FirstAsync();
            //if (telgramRecord == null || telgramRecord.ID <= 0 || telgramRecord.TelegramUniqueIDJson != telegramUniqueIDJson)
            //{
            //    var telegramRecordInfo = new TelegramRecordInfo()
            //    {
            //        ID = _Snowflake.GetId(),
            //        EquipmentCode = scanPlcMessage.EquipmentCode,
            //        TelegramUniqueIDJson = telegramUniqueIDJson,
            //        PlcTelegramJson = JsonConvert.SerializeObject(scanPlcMessage),
            //        WcsTelegramJson = JsonConvert.SerializeObject(wcsMessage),
            //        CreateTime = DateTime.Now,
            //        UpdateTime = DateTime.Now
            //    };
            //    await _TelegramRecordInfoRepository.InsertAsync(telegramRecordInfo);
            //}
            //else
            //{
            //    telgramRecord.UpdateTime = DateTime.Now;
            //    await _TelegramRecordInfoRepository.UpdateAsync(telgramRecord);
            //}

            #region 握手类型不处理逻辑 
            /*
             * 0 0 不处理
             * 0 1 不处理
             * 1 0 处理组盘业务
             * 0 1 清理wcs报文
             */
            if (wcsMessage == null)
            {
                return;
            }
            //交互空闲
            if (plcMessage.ActionType == 0 && wcsMessage.ActionType == 0)
            {
                _LogUtil.Info($"交互空闲({typeof(PlanarBatteryScanPlcActionBOMessageService).Name})处理成功：设备{plcActionMessage.EquipmentCode}交互空闲");
                return;
            }
            //等待执行
            if (plcMessage.ActionType == 1 && wcsMessage.ActionType == 1)
            {
                _LogUtil.Info($"等待执行({typeof(PlanarBatteryScanPlcActionBOMessageService).Name})处理成功：设备{plcActionMessage.EquipmentCode}等待执行");
                return;
            }
            #endregion

            //1. 验证plc是否在线
            //if (plcStateBo.PlcState == 0)
            //{
            //    _LogUtil.Info($"[平面设备扫码报文服务]处理失败：设备({scanPlcMessage.EquipmentCode})PLC({plcConnect.IP})已离线");
            //    return;
            //}

            //4. 组织报文，写入plc
            var objectType = typeof(PlanarGeneralWriteWcsAction).Name;
            var writeConfig = await _PlcWriteDbInfoRepository.GetFirstAsync(s => s.EquipmentCode == scanPlcMessage.EquipmentCode && s.ObjectType == objectType);
            if (writeConfig == null)
            {
                _LogUtil.Info($"[平面设备扫码报文服务]处理失败：设备号({scanPlcMessage.EquipmentCode})获取PLC写入配置失败");
                return;
            }

            //plc报文是什么握手类型则回什么握手类型
            PlanarGeneralWriteWcsAction writeBo = new PlanarGeneralWriteWcsAction(
                writeConfig.PlcConnectionId,
                writeConfig.ID,
                writeConfig.DbCode,
                writeConfig.DbStart,
                objectType,
                writeConfig.EquipmentCode.ToInt32(),
                scanPlcMessage.ActionType,
                scanPlcMessage.ToEquipmentCode,
                scanPlcMessage.TaskCode,
                scanPlcMessage.PalletBarcode,
                plcMessage.PalletType,
                alrmCode: plcMessage.AlrmCode);

            var plcConn = _PlcConnectionPool.S7GetWritePlcConnection(writeBo.PlcConnectionID);
            if (plcConn == null)
            {
                _LogUtil.Info($"[平面设备扫码报文服务]处理失败：设备号({writeBo.EquipmentCode})获取连接({writeBo.PlcConnectionID})失败");
                return;
            }


            


            //处理组盘&请求巷道（下发上架任务）业务
            if (scanPlcMessage.ActionType == 1 && wcsMessage.ActionType == 0)
            {
                //托盘号不存在 写入握手类型100报警
                if (string.IsNullOrEmpty(scanPlcMessage.PalletBarcode))
                {
                    _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配失败：设备编号{writeBo.EquipmentCode}托盘信息不存在！");
                    writeBo.ActionType = 0;
                    var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                    if (writeBl == false)
                    {
                        _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配处理失败：PLC(IP{plcConn.IP},设备编号{writeBo.EquipmentCode})写入报文失败");
                    }
                    else
                    {
                        _LogUtil.Info($"AisleRequestService发送报文  PLCId:{writeBo.PlcConnectionID} DBId:{writeBo.PlcWriteDbID}  设备编号{writeBo.EquipmentCode} WCS握手{writeBo.ActionType}");
                    }
                    return;
                }

                //wms组盘
                try
                {
                    WCSCombinePalletInfoDto wCSCombinePalletInfoDto = new WCSCombinePalletInfoDto();
                    wCSCombinePalletInfoDto.ContainerBarcode = scanPlcMessage.PalletBarcode;
                    wCSCombinePalletInfoDto.EquipmentCode = scanPlcMessage.EquipmentCode;

                    List<WCSOneBatteryDto> list = GetBatteryDto(batteryScanPlcAction);
                    wCSCombinePalletInfoDto.oneBatteryInfoDtos = list;
                    //组盘提交数据到WMS
                    var bo = await WCSMessageWithWMSApi.WCSAddComPalletAsync(wCSCombinePalletInfoDto);

                    if (!bo)
                        _LogUtil.Error($"[平面设备扫码报文服务]处理失败：设备号({scanPlcMessage.EquipmentCode})扫码组盘失败");

                }
                catch (Exception ex)
                {
                    _LogUtil.Error($"[平面设备扫码报文服务]处理失败：设备号({scanPlcMessage.EquipmentCode})扫码组盘异常：{ex.Message}");
                }

                #region 分配巷道


                #region 上架任务已存在逻辑处理


                //判断设备在wcs是否已存在分配巷道任务
                var exp = Expressionable.Create<WorkTaskInfo>();
                exp.AndIF(true, (a) => a.PalletCode == scanPlcMessage.PalletBarcode && (a.TaskState == EnumTaskState.Initial || a.TaskState == EnumTaskState.Executing));
                var wcsWorkTaskInfo = await _workTaskInfoRepository.GetFirstAsync(exp.ToExpression());
                //根据托盘是否存在其它的任务 && 起点位置是否相同判断，存在则写入正常报文Return
                if (wcsWorkTaskInfo != null && wcsWorkTaskInfo.CurrentFromEquipment == scanPlcMessage.EquipmentCode)
                {
                    _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配重复：设备编号{scanPlcMessage.EquipmentCode}，任务号：{wcsWorkTaskInfo.TaskCode}入库任务已存在！");

                    //针对wcs任务为初始化的处理成执行中并同步更新wms任务状态
                    if (wcsWorkTaskInfo.TaskState == EnumTaskState.Initial || wcsWorkTaskInfo.TaskState == EnumTaskState.Executing)
                    {
                        wcsWorkTaskInfo.TaskState = EnumTaskState.Executing;
                        wcsWorkTaskInfo.UpdateTime = DateTime.Now;
                        wcsWorkTaskInfo.CurrentDetailTaskState = EnumDetailTaskState.Executing;
                        try
                        {
                            //同步更新wms任务状态
                            var flag = await WCSMessageWithWMSApi.WCSUpdateWMStaskStateAndProcessTaskStateAsync(wcsWorkTaskInfo.WmsTaskCode, (int)EnumTaskState.Executing);
                            if (flag)
                            {
                                wcsWorkTaskInfo.UploadWmsState = EnumUploadWmsState.Succeed;
                                wcsWorkTaskInfo.UploadWmsTime = DateTime.Now;
                            }
                        }
                        catch (Exception ex)
                        {
                            _LogUtil.Error($"[平面设备扫码报文服务]请求巷道分配重复：设备编号{writeBo.EquipmentCode}wms任务号{wcsWorkTaskInfo.TaskCode}同步状态更新失败{ex.ToString()}！");
                        }
                        //更新wcs任务状态为执行中
                        await _workTaskInfoRepository.UpdateAsync(wcsWorkTaskInfo);
                    }

                    //写入正常报文
                    writeBo.TaskCode = wcsWorkTaskInfo.TaskCode;
                    writeBo.PalletBarcode = wcsWorkTaskInfo.PalletCode;
                    writeBo.ToEquipmentCode = wcsWorkTaskInfo.CurrentToEquipment.ToInt32();
                    var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                    if (!writeBl)
                    {
                        _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配处理失败：PLC(IP{plcConn.IP},设备编号{writeBo.EquipmentCode})写入报文失败");
                        return;
                    }
                    else
                    {
                        _LogUtil.Info($"AisleRequestService发送报文  PLCId:{writeBo.PlcConnectionID} DBId:{writeBo.PlcWriteDbID}  设备编号{writeBo.EquipmentCode} WCS握手{writeBo.ActionType}");
                    }
                    return;
                }
                #endregion

                #region wcs托盘上架任务NA逻辑处理
                WmsTaskInfoDto workTaskDto = null;
                try
                {
                    //向wms读取巷道分配任务
                    WMSApiDomain.WebApi.HeaderResult<WmsTaskInfoDto> res = await WCSMessageWithWMSApi.WCSCreatUploadWarehouseWMSTaskAsync(plcMessage.PalletBarcode, plcMessage.EquipmentCode);
                    if (res.IsSucceed)
                    {
                        workTaskDto = res.Result;
                    }
                    else
                    {
                        var msg = res.Message;
                        //runLogInfo.RunLog = $"向Wms请求任务失败:{msg}";
                        //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    _LogUtil.Error($"[平面设备扫码报文服务]请求巷道分配失败：Wms请求任务失败，托盘号{scanPlcMessage.PalletBarcode}，设备编号{scanPlcMessage.EquipmentCode}！异常：{ex.ToString()}");
                }

                //wms请求失败处理 写入100报警握手类型
                if (workTaskDto == null)
                {
                    _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配失败：Wms请求任务失败，托盘号{plcMessage.PalletBarcode}，设备编号{plcMessage.EquipmentCode}！");
                    writeBo.ActionType = 0;
                    var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                    if (writeBl == false)
                    {
                        _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配处理失败：PLC(IP{plcConn.IP},设备编号{writeBo.EquipmentCode})写入报文失败");
                    }
                    else
                    {
                        _LogUtil.Info($"AisleRequestService发送报文  PLCId:{writeBo.PlcConnectionID} DBId:{writeBo.PlcWriteDbID}  设备编号{writeBo.EquipmentCode} WCS握手{writeBo.ActionType}");
                    }
                    return;
                }

                //WorkTaskInfo数据补全
                var workTaskInfo = new WorkTaskInfo();
                long id = _Snowflake.GetId();
                workTaskInfo.ID = id;
                //wcs任务code从wmstaskcode日开始截取
                int.TryParse(workTaskDto.TaskCode.ToString().Substring(6), out var wcsTaskCode);
                workTaskInfo.TaskCode = wcsTaskCode;
                //wms赋值
                workTaskInfo.WmsTaskCode = workTaskDto.TaskCode;
                workTaskInfo.DependWmsTaskCode = workTaskDto.DependWMSTaskCode;
                workTaskInfo.TaskType = Enum.Parse<EnumTaskType>(workTaskDto.TaskType.ToString());

                workTaskInfo.WmsFromPosition = workTaskDto.StartPosition;
                workTaskInfo.WmsToPosition = workTaskDto.EndPosition;
                workTaskInfo.WmsFromStation = workTaskDto.FromStation;
                workTaskInfo.WmsToStation = workTaskDto.ToStation;
                workTaskInfo.TaskProcessState = EnumTaskProcessState.Initial;
                workTaskInfo.TaskState = EnumTaskState.Executing;
                workTaskInfo.Priority = workTaskDto.Priority;

                //托盘条码
                workTaskInfo.PalletCode = scanPlcMessage.PalletBarcode;

                #region 任务子任务信息赋值by RouteDetailInfo
                //获取配置巷道信息
                var routeConfigExp = Expressionable.Create<RouteInfo>();
                routeConfigExp.AndIF(true, (a) => a.FromStation == workTaskInfo.WmsFromStation && a.ToStation == workTaskInfo.WmsToStation);
                var routeInfo = await _workTaskInfoRepository.AsSugarClient()
                    .Queryable<RouteInfo>()
                    .Where(routeConfigExp.ToExpression())
                    .Select((a) => new RouteInfo()
                    {
                        ID = a.ID,
                        FromStation = a.FromStation,
                        ToStation = a.ToStation,
                    }).FirstAsync();
                if (routeInfo == null)
                {
                    _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配处理失败：设备编号{writeBo.EquipmentCode}巷道路径信息，起始工位{workTaskInfo.WmsFromStation}目标工位{workTaskInfo.WmsToStation}获取失败");
                    return;
                }

                //巷道详情信息获取
                var routeDetailConfigExp = Expressionable.Create<RouteDetailInfo>();
                routeDetailConfigExp.AndIF(true, (a) => a.RouteID == routeInfo.ID && a.IsStart);
                var routeDetailInfo = await _workTaskInfoRepository.AsSugarClient()
                    .Queryable<RouteDetailInfo>()
                    .Where(routeDetailConfigExp.ToExpression())
                    .Select((a) => new
                    {
                        ID = a.ID,
                        RouteID = a.RouteID,
                        FromCargo = a.FromCargo,
                        ToCargo = a.ToCargo,
                        DispatchType = a.DispatchType,
                        FromEquipment = a.FromEquipment,
                        ToEquipment = a.ToEquipment,

                    }).FirstAsync();

                if (routeDetailInfo == null)
                {
                    _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配处理失败：设备编号{writeBo.EquipmentCode}巷道路径详情配置信息起始工位{workTaskInfo.WmsFromStation}目标工位{workTaskInfo.WmsToStation}获取失败");
                    return;
                }

                workTaskInfo.CurrentFromCargo = routeDetailInfo.FromCargo;
                workTaskInfo.CurrentToCargo = routeDetailInfo.ToCargo;
                workTaskInfo.RouteID = routeDetailInfo.RouteID;
                workTaskInfo.CurrentRounteDetailID = routeDetailInfo.ID;
                workTaskInfo.CurrentDispatchType = routeDetailInfo.DispatchType;
                //起始设备位 
                workTaskInfo.CurrentFromEquipment = workTaskInfo.WmsFromPosition; //WMS 作业实际起点设备
                workTaskInfo.CurrentToEquipment = routeDetailInfo.ToEquipment;
                workTaskInfo.CurrentDetailTaskState = EnumDetailTaskState.Executing;
                workTaskInfo.CurrentCreateTime = DateTime.Now;
                workTaskInfo.CurrentUpdateTime = DateTime.Now;
                #endregion

                workTaskInfo.SaveTime = DateTime.Now;
                workTaskInfo.UpdateTime = DateTime.Now;

                #region 同步更新wms任务状态&写入正常报文
                try
                {
                    //同步更新wms任务状态为执行中
                    var flag = await WCSMessageWithWMSApi.WCSUpdateWMStaskStateAndProcessTaskStateAsync(workTaskInfo.WmsTaskCode, (int)EnumTaskState.Executing);
                    if (flag)
                    {
                        workTaskInfo.UploadWmsState = EnumUploadWmsState.Succeed;
                        workTaskInfo.UploadWmsTime = DateTime.Now;
                    }
                }
                catch (Exception ex)
                {
                    _LogUtil.Error($"[平面设备扫码报文服务]请求巷道分配失败：设备编号{writeBo.EquipmentCode}wms任务号{workTaskInfo.TaskCode}同步状态更新失败{ex.ToString()}！");
                }

                //WorkTaskInfo数据插入
                bool bl = true;
                try
                {
                    bl = await _workTaskInfoRepository.InsertAsync(workTaskInfo);
                }
                catch(Exception ex)
                {
                    _LogUtil.Error($"[平面设备扫码报文服务]wcs生成任务失败{ ex.ToString()}");
                    return;
                }

                //写入正常报文到Plc
                writeBo.TaskCode = workTaskInfo.TaskCode;//wcs任务号
                writeBo.ToEquipmentCode = workTaskInfo.CurrentToEquipment.ToInt32();//目标设备编号
                var writeResult = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                if (writeResult == false)
                {
                    _LogUtil.Info($"[平面设备扫码报文服务]请求巷道分配处理失败：PLC(IP{plcConn.IP},设备编号{writeBo.EquipmentCode})写入报文失败");
                    return;
                }
                else
                {
                    _LogUtil.Info($"AisleRequestService发送报文  PLCId:{writeBo.PlcConnectionID} DBId:{writeBo.PlcWriteDbID}  设备编号{writeBo.EquipmentCode} WCS握手{writeBo.ActionType}");
                }
                #endregion

                #endregion

                #endregion
            }

            //清理wcs报文
            if (scanPlcMessage.ActionType == 0 && wcsMessage.ActionType == 1)
            {
                writeBo.ActionType = 0;
                writeBo.ToEquipmentCode = 0;
                writeBo.TaskCode = 0;
                writeBo.PalletBarcode = "";
                _LogUtil.Info($"[平面设备扫码报文服务]PLC(IP{plcConn.IP},设备{writeBo.EquipmentCode})握手类型 0 1 清空数据开始");
                var writeResult = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                if (writeResult == false)
                {
                    _LogUtil.Info($"[平面设备扫码报文服务]处理失败：PLC(IP{plcConn.IP},设备{writeBo.EquipmentCode})写入报文失败");

                    return;
                }
            }

            _LogUtil.Info($"[平面设备扫码报文服务]处理成功：PLC(IP{plcConn.IP},设备{plcMessage.EquipmentCode})");

        }

        public List<WCSOneBatteryDto> GetBatteryDto(PlanarBatteryScanPlcActionBO batteryScanPlcAction)
        {
            List<WCSOneBatteryDto> oneBatteryInfoDtos = new List<WCSOneBatteryDto>();
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 1,
                BatteryCode = batteryScanPlcAction.BatteryCode1
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 2,
                BatteryCode = batteryScanPlcAction.BatteryCode2
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 3,
                BatteryCode = batteryScanPlcAction.BatteryCode3
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 4,
                BatteryCode = batteryScanPlcAction.BatteryCode4
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 5,
                BatteryCode = batteryScanPlcAction.BatteryCode5
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 6,
                BatteryCode = batteryScanPlcAction.BatteryCode6
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 7,
                BatteryCode = batteryScanPlcAction.BatteryCode7
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 8,
                BatteryCode = batteryScanPlcAction.BatteryCode8
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 9,
                BatteryCode = batteryScanPlcAction.BatteryCode9
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 10,
                BatteryCode = batteryScanPlcAction.BatteryCode10
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 11,
                BatteryCode = batteryScanPlcAction.BatteryCode11
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 12,
                BatteryCode = batteryScanPlcAction.BatteryCode12
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 13,
                BatteryCode = batteryScanPlcAction.BatteryCode13
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 14,
                BatteryCode = batteryScanPlcAction.BatteryCode14
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 15,
                BatteryCode = batteryScanPlcAction.BatteryCode15
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 16,
                BatteryCode = batteryScanPlcAction.BatteryCode16
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 17,
                BatteryCode = batteryScanPlcAction.BatteryCode17
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 18,
                BatteryCode = batteryScanPlcAction.BatteryCode18
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 19,
                BatteryCode = batteryScanPlcAction.BatteryCode19
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 20,
                BatteryCode = batteryScanPlcAction.BatteryCode20
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 21,
                BatteryCode = batteryScanPlcAction.BatteryCode21
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 22,
                BatteryCode = batteryScanPlcAction.BatteryCode22
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 23,
                BatteryCode = batteryScanPlcAction.BatteryCode23
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 24,
                BatteryCode = batteryScanPlcAction.BatteryCode24
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 25,
                BatteryCode = batteryScanPlcAction.BatteryCode25
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 26,
                BatteryCode = batteryScanPlcAction.BatteryCode26
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 27,
                BatteryCode = batteryScanPlcAction.BatteryCode27
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 28,
                BatteryCode = batteryScanPlcAction.BatteryCode28
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 29,
                BatteryCode = batteryScanPlcAction.BatteryCode29
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 30,
                BatteryCode = batteryScanPlcAction.BatteryCode30
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 31,
                BatteryCode = batteryScanPlcAction.BatteryCode31
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 32,
                BatteryCode = batteryScanPlcAction.BatteryCode32
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 33,
                BatteryCode = batteryScanPlcAction.BatteryCode33
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 34,
                BatteryCode = batteryScanPlcAction.BatteryCode34
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 35,
                BatteryCode = batteryScanPlcAction.BatteryCode35
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 36,
                BatteryCode = batteryScanPlcAction.BatteryCode36
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 37,
                BatteryCode = batteryScanPlcAction.BatteryCode37
            });
            oneBatteryInfoDtos.Add(new WCSOneBatteryDto()
            {
                BatteryIndex = 38,
                BatteryCode = batteryScanPlcAction.BatteryCode38
            });

            return oneBatteryInfoDtos;
        }

    }
}
